<template>
  <view>
    <view class="container" v-if="isShow">
      <!-- 顶部导航 -->
      <custom-header title="卖卡"></custom-header>

      <!-- 可滑动卡片类型 -->
      <view class="card-scroll-placeholder"></view>
      <scroll-view scroll-x class="card-scroll-container" show-scrollbar="false">
        <view v-for="(item, index) in typeList" :key="index"
              :class="['type-item', selectedIndex === index ? 'active' : '']" @click="switchCardType(index)">
          {{ item.name }}
        </view>
      </scroll-view>

      <view class="content-container">
        <!-- 卡种选择 -->
        <view class="form-item" @click="showCardPopup">
          <text class="label">卡种</text>
          <view class="form-item-right">
            <image style="height: 32rpx; width: 32rpx; margin-right: 12rpx;" :src="cardUrl"
                   v-if="cardName !== '请选择'"></image>
            <text class="hint" :class="{active : cardName !== '请选择'}">{{ cardName }}</text>
            <image src="../../static/images/arrow_right.png" style="width: 15rpx; height: 27rpx;"></image>
          </view>
        </view>

        <view class="divider"></view>

        <!-- 面值选择 -->
        <view class="form-item" @click="showFvPopup">
          <text class="label">面值</text>
          <view class="form-item-right">
            <text class="hint" :class="{active : faceValue !== '请选择'}">{{ faceValue }}</text>
            <image src="../../static/images/arrow_right.png" style="width: 15rpx; height: 27rpx;"></image>
          </view>
        </view>

        <view
            style="text-align: right; font-size: 20rpx; color: rgba(0, 0, 0, 0.40); margin-right: 42rpx; margin-bottom: 22rpx;">
          回收价格由输入折扣决定
        </view>

        <view class="divider"></view>
      </view>

      <view class="select-container">
        <!-- 折扣 -->
        <view class="discount-item" v-if="faceValue !== '请选择'">
          <view class="fixed-discount">
            <text class="label">折扣</text>

            <view class="form-item-right" v-if="rateModel == 'rate'">
              <text class="label">{{ rate }}</text>
              <image src="../../static/images/arrow_right.png" style="width: 15rpx; height: 27rpx;">
              </image>
            </view>

            <view class="right-container" v-if="rateModel == 'raterang'">
              <input class="discount-input" v-model="customRate" placeholder="请输入费率"
                     placeholder-class="ph-style"></input>
            </view>

            <view class="right-container" v-if="rateModel == 'customfacevalue'">
              <input class="discount-input" v-model="customFace" placeholder="请输入面值" @input="findRate"
                     placeholder-class="ph-style"></input>
              <text class="custom-last">元</text>
            </view>

          </view>

          <view
              style="text-align: right; font-size: 20rpx; color: rgba(0, 0, 0, 0.40); margin-right: 42rpx; margin-bottom: 22rpx;"
              v-if="rateModel == 'raterang'">
            {{ rateRange }}
          </view>

          <view
              style="text-align: right; font-size: 20rpx; color: rgba(0, 0, 0, 0.40); margin-right: 42rpx; margin-bottom: 22rpx;"
              v-if="rateModel == 'customfacevalue'">
            {{ currentRate }}
          </view>
        </view>

        <!-- 可用额度 -->
        <view class="user-limit">
          <text style="font-size: 28rpx; color: rgba(0, 0, 0, 0.60);">今天可用额度</text>
          <text
              style="color: rgba(0, 0, 0, 0.60); padding: 4rpx 20rpx; font-size: 28rpx; background-color: #FDC74A; border-radius: 26rpx;">
            ￥{{ $app.getSellCardQuota() ? $app.getSellCardQuota() : 0 }}
          </text>
        </view>

        <!-- 提交方式切换 -->
        <view class="sub-type-container">
          <view class="submit-type">
            <view :class="['type-btn', submitType === 1 ? 'active' : '']" @click="submitType = 1">
              单卡提交
            </view>
            <view :class="['type-btn', submitType === 2 ? 'active' : '']" @click="submitType = 2"
                  v-if="!isSimpleCommit">
              批量提交
            </view>
          </view>
        </view>

        <!-- 卡号卡密输入 -->
        <view class="input-container">
          <view class="input-group" v-if="submitType == 1">
            <view class="group-input" v-if="isHaveCardNumber">
              <view class="label">
                卡号
              </view>
              <input class="card-input" placeholder="请输入卡号" v-model="cardNumber"
                     placeholder-class="ph-style"/>
            </view>
            <view class="group-input">
              <view class="label">
                卡密
              </view>
              <input class="card-input" placeholder="请输入卡密" v-model="cardPassword"
                     placeholder-class="ph-style"/>
            </view>
          </view>

          <textarea v-else v-model="inputText" placeholder="请输入卡号和卡密（格式：卡号后空格接卡密，换行输入下一组）"
                    @input="formatInput" class="card-input-area" placeholder-class="ph-style" maxlength="-1"/>

          <!-- 提示信息 -->
          <view class="tips">
            <text class="warning">{{ tip }}</text>
          </view>

          <view style="margin-top: 10rpx;">
            <view style="color: black; font-size: 24rpx; font-weight: bold;">提交说明</view>
            <text style="color: #999; font-size: 22rpx;">1、官方电话:400-189-3918 在线咨询工作时间
              08:00-23:00\n2、提交前仔细核对充值卡/卡券，卡号、卡密正确无误，提交错误的卡号、卡密，将无法兑换成功。\n3、请仔细核对充值卡的面值，如提交充值卡与实际面值不符，可能导致无法结算，给您带来损失。\n4、平台24小时可提交兑换，可随时提现，系统自动处理\n5、为保证您的账户安全，请配合平台做好相关身份认证，不同的认证等级，结算额度也是不一样的。\n6、请确保充值卡来源合法，惠收卡拒绝一切通过非法手段获取的充值卡，一经发现异常情况，惠收卡有义务向公安机关反应。
            </text>
          </view>
          <view style="height: 150rpx; "></view>
        </view>

        <!-- 提交按钮 -->
        <!-- <view @click="validateUserState()" class="submit-btn"
          :style="{backgroundColor: isMaintain ? '#B7D3FF' : '#4D7EF4'}">提交卖卡</view> -->
        <view class="submit-btn">
          <view @click="toCustomer()"
                style="display: flex; height: 100%;align-items: center;justify-content: center; background: white; padding: 0 20rpx;">
            <image style="height: 25rpx; width: 25rpx;" src="/static/images/ic_mine_customer.png"></image>
            <view style=" word-wrap: normal; white-space: nowrap;">联系客服</view>
          </view>
          <text
              style="width: calc(100% - 70rpx);background: #4D7EF4;color: white;text-align: center;font-size: 28rpx; display: flex; align-items: center; justify-content: center;"
              @click="validateUserState()">提交卖卡
          </text>
        </view>
      </view>

      <!-- 选择卡片 -->
      <u-popup :show="isShowCardPopup" mode="bottom" round="20" @close="closeCardPop">
        <view class="popup-container">
          <view class="popup-header">
            <text class="title">选择卡种</text>
            <image class="close" @tap="closeCardPop" src="../../static/images/ic_pop_close.png"></image>
          </view>

          <u-grid col="3" :border="false">
            <u-grid-item v-for="(item, index) in cardList" :key="index" @click="switchCard(index)">
              <view class="card-item-container">
                <text class="card-item-state" v-if="item.isMaintain == 1">维护中</text>
                <image class="item-image" :src="item.mimg" mode="aspectFit"></image>
                <text class="card-item-name">{{ item.name }}</text>
              </view>
            </u-grid-item>
          </u-grid>
        </view>
      </u-popup>

      <!-- 选择面值 -->
      <u-popup :show="isShowFvPopup" mode="bottom" round="20" @close="closeFvPop">
        <view class="popup-container">
          <view class="popup-header">
            <text class="title">选择面值</text>
            <image class="close" @tap="closeFvPop" src="../../static/images/ic_pop_close.png"></image>
          </view>

          <u-grid col="3" :border="false">
            <u-grid-item v-for="(item, index) in faceValueList" :key="index" @click="switchFace(index)">
              <view class="card-item-fv-container">
                <text class="card-item-state" v-if="isMaintain">维护中</text>
                <text class="card-item-name">￥{{ item.faceValue == 0 ? "自定义" : item.faceValue }}</text>
                <view style="margin-top: 12rpx; font-size: 24rpx;">
                  <text
                      style="color: #626262; margin-right: 22rpx;">￥{{ item.showAmount ? item.showAmount : '-' }}
                  </text>
                  <text style="color: #4D7EF4;">{{ item.showRate ? item.showRate : '-' }}折</text>
                </view>
              </view>
            </u-grid-item>
          </u-grid>
        </view>
      </u-popup>

      <!-- 提交提示 -->
      <u-popup :show="isShowCommitPopup" mode="bottom" round="20" @close="closeCommitPop">
        <view class="commit-popup-container">
          <view
              style="display: flex; align-items: center; background-color: #FFFBE8; border-radius: 16rpx; padding: 20rpx 16rpx;">
            <image src="../../static/images/ic_sale-pop.png"></image>
            <text style="font-size: 24rpx; color: #ED6A0C; margin-left: 18rpx;">注意：面值不符，余额不退！</text>
          </view>

          <view
              style="padding: 24rpx; background-color: #F0F0F0; display: flex; align-items: center; margin-bottom: 24rpx;">
            <text style="flex: 1; margin-right: 32rpx; font-size: 24rpx; color: black;">我已阅读并同意
              <text
                  style="color: #4D7EF4;"
                  @click="toDetail('https://file.huishouka.com.cn/html/1742964957582.html')">《回收说明》
              </text>
              和
              <text
                  style="color: #4D7EF4;"
                  @click="toDetail('https://file.huishouka.com.cn/html/1742964888037.html')">《转让协议》
              </text>
            </text>
            <image
                :src="commitPopOne?'../../static/images/ic_radio_true.png':'../../static/images/ic_radio_false.png'"
                @click="changeCommitPopOne"></image>
          </view>

          <view
              style="padding: 24rpx; background-color: #F0F0F0; display: flex; align-items: center; margin-bottom: 54rpx;">
            <text
                style="flex: 1; margin-right: 32rpx; font-size: 24rpx; color: black;">我确认该卡号卡密来源合法，如有问题，本人愿意承担一切法律责任。
            </text>
            <image
                :src="commitPopTwo?'../../static/images/ic_radio_true.png':'../../static/images/ic_radio_false.png'"
                @click="changeCommitPopTwo"></image>
          </view>

          <view style="display: flex; font-size: 28rpx;">
            <view
                style="flex: 1; text-align: center; margin-right: 26rpx; padding: 18rpx 0; background-color: white; border: #4D7EF4 solid 2rpx; border-radius: 8rpx; color: #4D7EF4;"
                @click="closeCommitPop">
              取消
            </view>
            <view
                style="flex: 1; text-align: center; padding: 18rpx 0; background-color: #4D7EF4; color: white; border-radius: 8rpx;"
                @click="handleSubmit">
              确认
            </view>
          </view>
        </view>
      </u-popup>

      <u-popup :show="showAuthPopup" @close="closeAuthPop()" bgColor="transparent" mode="center">
        <view class="popup-auth-container">
          <image
              style="width: 32rpx; height: 32rpx; align-self: flex-end; margin-top: 32rpx; margin-right: 38rpx;"
              src="/static/images/ic_auth_pop_close.png" @click="closeAuthPop"></image>
          <image style="width: 190rpx; height: 146rpx; align-self: center;"
                 src="/static/images/ic_auth_pop_icon.png"></image>
          <view
              style="text-align: center; margin-top: 48rpx; font-size: 48rpx; color: #0C0C0C; font-weight: 500;">
            实名认证
          </view>
          <view style="text-align: center; margin-top: 28rpx; font-size: 32rpx; color: rgba(0, 0, 0, 0.63);">
            {{ getAuthText() }}
          </view>
          <view
              style="margin-left: 86rpx; margin-right: 86rpx; text-align: center; margin-top: 60rpx; padding: 18rpx 0; border-radius: 41rpx; background-color: #2F7FFC; color: white; font-size: 32rpx;"
              @click="toRealNameList()">去完成
          </view>
        </view>
      </u-popup>

      <u-popup :show="showTipPopup" @close="closeTipPop()" round="36rpx" mode="center" :safeAreaInsetBottom="false">
        <view>
          <view style="text-align: center; margin-top: 30rpx; font-size: 32rpx; color: #000; font-weight: bold;">
            温馨提示</view>
          <view style="text-align: center; margin-top: 34rpx; font-size: 28rpx; color: #5C6166; margin-left: 40rpx; margin-right: 40rpx">
            您已复制微信客服链接,请使用浏览器打开</view>
          <view style="width: 100%; height: 2rpx; background-color: #F0F0F0; margin-top: 46rpx;"></view>
          <view
              style="text-align: center; margin-top: 20rpx; margin-bottom: 20rpx; font-size: 32rpx; color: #000; font-weight: bold;"
              @click="closeTipPop()">
            我知道了</view>
        </view>
      </u-popup>
    </view>
  </view>
</template>

<script>
export default {
  onLoad(options) {
    this.imgHost = this.$app.imgApiHost;
    if (options) {
      console.log("类型id" + options.typeId + "卡片id" + options.cardId)
      this.typeId = parseInt(options.typeId);
      this.cardId = parseInt(options.cardId);
    }
    this.getTypeList(true);
  },
  data() {
    return {
      typeList: [], //类型列表
      typeId: null, //当前类型
      selectedIndex: 0, //类型下标
      cardList: [], //卡片列表
      cardId: null, //当前卡片
      selectedCardIndex: 0, //卡片下标
      faceValueList: [], //面值列表
      faceId: null, //当前面值
      selectedFaceIndex: 0, //面值下标
      faceValue: '请选择', //固定面值
      rate: null, //当前固定费率
      rateModel: '', //费率模式 rate固定费率 raterang自定义费率 fixed固定金额 customfacevalue自定义面值
      cardName: '请选择', //卡片名字
      cardUrl: '', //卡片图标
      submitType: 1, // 1-单卡 2-批量
      isShowFvPopup: false,
      isShowCardPopup: false,
      isShowCommitPopup: false,
      cardNumber: '', // 单卡号
      cardPassword: '', // 单卡密
      cardsResult: '', // 最终卡拼接
      inputText: '', // 批量输入格式化
      cardNumberLength: 5, // 卡号长度（示例）
      cardKeyLength: 5, // 卡密长度（示例）
      isHaveCardNumber: true, //是否有卡号
      isSimpleCommit: false, //是否只能单卡
      tip: '', //提示
      isMaintain: false, //当前卡是否维护
      customRate: null, //自定义费率
      customFace: null,
      imgHost: '',
      commitPopOne: false,
      commitPopTwo: false,
      rateRange: '', // 自定义费率范围
      currentRate: '输入面值查看费率', // 自定义面值，当前找到的费率
      rateData: [],
      showAuthPopup: false,
      isShow: uni.getStorageSync("isShow"),
      showTipPopup: false,
    }
  },
  methods: {
    closeTipPop() {
      this.showTipPopup = false;
    },
    toRealNameList() {
      uni.navigateTo({
        url: '/pages/real-name-list/real-name-list'
      })
    },
    // 获取类型列表
    async getTypeList(isInit) {
      try {
        const res = await this.$http({
          method: 'GET',
          url: '/product/type/list',
        });
        this.typeList = res.data.filter(item => item.name !== '热门回收');

        this.$nextTick(() => {
          if (this.typeId && isInit) {
            // 查找匹配的索引
            const targetIndex = this.typeList.findIndex(
                tab => tab.id === this.typeId
            )
            if (targetIndex > -1) {
              this.selectedIndex = targetIndex;
              this.typeId = this.typeList[this.selectedIndex].id
            }
          } else {
            this.selectedIndex = 0;
            this.typeId = this.typeList[0].id;
          }

          this.getCardList(isInit);
        })
      } catch (error) {
        //TODO handle the exception
        console.log(error);
      }
    },
    // 获取卡片列表
    async getCardList(isInit) {
      try {
        const res = await this.$http({
          method: 'GET',
          url: '/product/product/list',
          data: {
            prodTypeId: this.typeList[this.selectedIndex].id
          }
        });
        console.log(res.data)
        this.cardList = res.data;

        this.$nextTick(() => {
          if (this.cardId && isInit) {
            // 查找匹配的索引
            const targetIndex = this.cardList.findIndex(
                tab => tab.id === this.cardId
            )
            if (targetIndex > -1) {
              this.clearInputs();

              this.selectedCardIndex = targetIndex;
              this.cardId = this.cardList[this.selectedCardIndex].id;
              this.cardName = this.cardList[this.selectedCardIndex].name;
              this.cardUrl = this.cardList[this.selectedCardIndex].mimg;
              this.tip = this.cardList[this.selectedCardIndex].tip;
              this.isMaintain = this.cardList[this.selectedCardIndex].isMaintain == 1;
              this.cardNumberLength = this.cardList[this.selectedCardIndex].cardDigit ? this
                  .cardList[this.selectedCardIndex].cardDigit : 0;
              this.cardKeyLength = this.cardList[this.selectedCardIndex].secretDigit ? this
                  .cardList[this.selectedCardIndex].secretDigit : 0;
              this.validateIsHave();
              this.validateIsSimple();
            }
          } else {
            this.clearInputs();

            this.selectedCardIndex = 0;
            this.cardId = this.cardList[this.selectedCardIndex].id;
            this.cardName = this.cardList[this.selectedCardIndex].name;
            this.cardUrl = this.cardList[this.selectedCardIndex].mimg;
            this.tip = this.cardList[this.selectedCardIndex].tip;
            this.isMaintain = this.cardList[this.selectedCardIndex].isMaintain == 1;
            this.cardNumberLength = this.cardList[this.selectedCardIndex].cardDigit ? this
                .cardList[this.selectedCardIndex].cardDigit : 0;
            this.cardKeyLength = this.cardList[this.selectedCardIndex].secretDigit ? this
                .cardList[this.selectedCardIndex].secretDigit : 0;
            this.validateIsHave();
            this.validateIsSimple();
          }

          this.getFaceValue();
        })
      } catch (error) {
        //TODO handle the exception
        console.log(error);
      }
    },
    // 获取面值列表
    async getFaceValue() {
      // 清空面值
      this.clearFace();
      const res = await this.$http({
        method: 'GET',
        url: '/product/faceValue/list',
        data: {
          prodId: this.cardId
        }
      });
      if (res) {
        this.faceValueList = res.data;
        this.showFvPopup()
      }
    },
    // 类型选择
    switchCardType(index) {
      if (index == this.selectedIndex) return;
      this.selectedIndex = index;
      this.typeId = this.typeList[this.selectedIndex].id;

      this.getCardList(false);
    },
    // 卡片选择
    switchCard(index) {
      this.closeCardPop();
      this.clearInputs();

      this.selectedCardIndex = index;
      this.cardId = this.cardList[this.selectedCardIndex].id;
      this.cardName = this.cardList[this.selectedCardIndex].name;
      this.cardUrl = this.cardList[this.selectedCardIndex].mimg;
      this.tip = this.cardList[this.selectedCardIndex].tip;
      this.isMaintain = this.cardList[this.selectedCardIndex].isMaintain == 1;
      this.cardNumberLength = this.cardList[this.selectedCardIndex].cardDigit ? this.cardList[this
          .selectedCardIndex].cardDigit : 0;
      this.cardKeyLength = this.cardList[this.selectedCardIndex].secretDigit ? this.cardList[this
          .selectedCardIndex].secretDigit : 0;
      this.validateIsHave();
      this.validateIsSimple();

      this.getFaceValue();
    },
    // 面值选择
    switchFace(index) {
      this.closeFvPop();

      this.selectedFaceIndex = index;
      //选中面值id
      this.faceId = this.faceValueList[this.selectedFaceIndex].fvId;
      //选中费率模式
      this.rateModel = this.faceValueList[this.selectedFaceIndex].rateModel;
      //选中的面值
      this.faceValue = this.rateModel == 'customfacevalue' ? '自定义面值' : this.faceValueList[this.selectedFaceIndex]
          .faceValue;
      //选中的费率
      this.rate = this.rateModel == 'rate' ? this.faceValueList[this.selectedFaceIndex].showRate : '';
      if (this.rateModel == 'raterang') {
        let rateArray = JSON.parse(this.faceValueList[this.selectedFaceIndex].rate);
        this.rateRange = `费率范围是 ${rateArray[0]} 到 ${rateArray[1]}`;
      }
      ;
      if (this.rateModel == 'customfacevalue') {
        this.rateData = JSON.parse(this.faceValueList[this.selectedFaceIndex].rate);
      }
    },
    // 清空面值
    clearFace() {
      this.faceId = null;
      this.selectedFaceIndex = 0;
      this.faceValue = '请选择';
      this.rateModel = null;
      this.rate = null;
    },
    toCustomer() {
      uni.setClipboardData({
        data: 'https://work.weixin.qq.com/kfid/kfc23a563ee7443bea4',
        success: function () {
          uni.hideToast();
        },
        fail: function (err) {
          uni.showToast({
            title: '复制失败',
            duration: 2000,
            icon: 'none'
          });
        }
      });
      this.showTipPopup = true;
    },
    validateUserState() {
      if (this.$app.isLogin()) {
        if (this.$app.getCredentialLevel() == 0) {
          this.showAuthPop();
        } else {
          if (this.faceId == null) {
            uni.showToast({
              title: '请选择面值',
              icon: 'none'
            });
            return;
          }

          if (this.rateModel == 'customfacevalue' && this.customFace == null) {
            uni.showToast({
              title: '请输入自定义面值',
              icon: 'none'
            });
            return;
          }
          // 判断额度是否大于2000
          const commitFace = this.rateModel == 'customfacevalue' ? this.customFace : this.faceValue
          console.log("总金额", parseFloat(commitFace) + parseFloat(this.$app.getTotalSettAmount()))
          if ((parseFloat(commitFace) + parseFloat(this.$app.getTotalSettAmount())) > 2000) {
            if (this.$app.getCredentialLevel() != 2) {
              this.showAuthPop();
            } else {
              this.showCommitPop();
            }
          } else {
            this.showCommitPop();
          }
        }
      } else {
        this.showModal("温馨提示", "您还未登录，快去登录吧", '/pages/login-nav/login-nav', 2);
      }
    },
    getAuthText() {
      if (this.$app.getCredentialLevel() == 0) {
        return "请完成初级认证，认证后可销卡和提现";
      } else {
        return "请完成高级认证，可提高每日销卡额度";
      }
    },
    showAuthPop() {
      this.showAuthPopup = true;
    },
    closeAuthPop() {
      this.showAuthPopup = false;
    },
    // state 0实名 1签署 2去登录
    showModal(title, content, url, state) {
      let modalConfirmText = ''
      if (state == 0) {
        modalConfirmText = '去实名';
      } else if (state == 1) {
        modalConfirmText = '去签署';
      } else {
        modalConfirmText = '去登录';
      }
      uni.showModal({
        title: title,
        content: content,
        cancelText: "关闭",
        confirmText: modalConfirmText,
        success: res => {
          if (res.confirm) {
            uni.navigateTo({
              url: url,
            })
          }
        }
      });
    },
    // 提交回收卡
    async handleSubmit() {
      //是否勾选
      if (!this.commitPopOne || !this.commitPopTwo) {
        uni.showToast({
          title: '请勾选协议',
          icon: 'none'
        });
        return;
      }

      // 维护状态
      if (this.isMaintain) {
        uni.showToast({
          title: '当前处于维护状态',
          icon: 'none'
        });
        return;
      }

      if (this.faceId == null) {
        uni.showToast({
          title: '请选择面值',
          icon: 'none'
        });
        return;
      }

      if (this.rateModel == 'customfacevalue' && this.customFace == null) {
        uni.showToast({
          title: '请输入自定义面值',
          icon: 'none'
        });
        return;
      }

      if (this.rateModel == 'raterang' && this.customRate == null) {
        uni.showToast({
          title: '请输入自定义费率',
          icon: 'none'
        });
        return;
      }

      // 输入空判断
      if (this.submitType == 1) {
        if (!this.validateInput()) return;
      } else {
        if (!this.inputText) return;
      }

      this.concatInputs();

      console.log(this.cardsResult);

      this.closeCommitPop();

      const res = await this.$http({
        method: 'POST',
        url: '/order/submit',
        data: {
          prodId: this.cardId,
          fvId: this.faceId,
          faceValue: this.rateModel == 'customfacevalue' ? this.customFace : '',
          discount: this.rateModel == 'raterang' ? this.customRate : '',
          cards: this.cardsResult,
          submitType: this.submitType
        }
      });

      if (res) {
        uni.showToast({
          title: '提交成功'
        });
        uni.switchTab({
          url: `/pages/order/order`
        })
      } else {
        uni.showToast({
          title: '提交失败'
        });
      }
      this.clearInputs();
    },
    validateInput() {
      if (this.isHaveCardNumber) {
        if (!this.cardNumber) {
          uni.showToast({
            title: '请输入卡号',
            icon: 'none'
          });
          return false;
        }
      }
      if (!this.cardPassword) {
        uni.showToast({
          title: '请输入卡密',
          icon: 'none'
        });
        return false;
      }
      return true;
    },
    // 找到当前面值对应费率
    findRate() {
      if (this.customFace === '' || this.customFace === null) {
        this.currentRate = '输入面值查看费率';
        return;
      }

      const customFace = parseFloat(this.customFace);

      // 遍历数据，找到对应的费率
      for (let i = 0; i < this.rateData.length; i++) {
        const item = this.rateData[i];
        if (!isNaN(customFace) && customFace >= item.min && customFace <= item.max) {
          this.currentRate = "当前面值费率是" + item.rate;
          return;
        }
      }

      // 如果没有找到对应的区间
      this.currentRate = '面值不在回收范围内';
    },
    // 是否有卡号
    validateIsHave() {
      this.isHaveCardNumber = this.cardList[this.selectedCardIndex].carmine == 1;
    },
    // 是否单卡提交
    validateIsSimple() {
      this.isSimpleCommit = this.checkCommitMode(this.cardList[this.selectedCardIndex].submitType);
    },
    // 展示面值弹窗
    showFvPopup() {
      this.isShowFvPopup = true;
    },
    // 关闭面值弹窗
    closeFvPop() {
      this.isShowFvPopup = false;
    },
    // 展示卡弹窗
    showCardPopup() {
      this.isShowCardPopup = true;
    },
    // 关闭卡弹窗
    closeCardPop() {
      this.isShowCardPopup = false;
    },
    // 展示提交确定弹窗
    showCommitPop() {
      this.isShowCommitPopup = true;
    },
    // 关闭提交确定弹窗
    closeCommitPop() {
      this.isShowCommitPopup = false;
    },
    // 协议一单选
    changeCommitPopOne() {
      this.commitPopOne = !this.commitPopOne;
    },
    // 协议二单选
    changeCommitPopTwo() {
      this.commitPopTwo = !this.commitPopTwo;
    },
    //卡参数拼接
    concatInputs() {
      if (this.submitType == 1) {
        this.cardsResult = this.isHaveCardNumber ? `${this.cardNumber},${this.cardPassword}` :
            `${this.cardPassword}`;
      } else {
        //没有校验规则
        if (this.cardNumberLength == 0 || this.cardKeyLength == 0) {
          console.log("没有校验规则，根据空格换行符自己拼接逗号");
          this.cardsResult = this.inputText.replaceAll(/\s+/g, ',');
          return;
        } else {
          console.log("有校验规则");
          const result = []
          this.inputText.split('\n').forEach(line => {
            if (this.isHaveCardNumber) {
              const [cardNumber, cardKey] = line.split(' ');
              if (cardNumber && cardKey) {
                result.push(`${cardNumber},${cardKey}`);
              }
            } else {
              const cardKey = line;
              if (cardKey) {
                result.push(cardKey);
              }
            }
          })
          // 最终拼接结果（实际调用接口提交）
          this.cardsResult = result.join(',')
        }
      }
    },
    // 清空提交
    clearInputs() {
      this.cardNumber = '';
      this.cardPassword = '';
      this.inputText = '';
      this.cardsResult = '';
    },
    // 判断几种提交方式
    checkCommitMode(str) {
      // 将字符串按逗号分割成数组后判断是否包含"2"
      return !str.split(',').includes('2');
    },
    formatInput(e) {
      const value = e.target ? e.target.value : e.detail.value
      console.log(value)

      if (this.cardNumberLength + this.cardKeyLength == 0) {
        this.inputText = value;
        return;
      }

      // 按行分割输入内容
      const lines = value.split('\n');
      const formattedLines = [];
      lines.forEach(line => {
        // 清理现有空格
        const newCleanLine = line.replace('-', '');
        const cleanLine = newCleanLine.replace(/\s/g, '');
        //计算卡号和卡密总长度
        const totalLength = this.cardNumberLength + this.cardKeyLength;

        // 按规则分组处理
        let processed = '';
        //开启循环，每次递增总长度
        for (let i = 0; i < cleanLine.length; i += totalLength) {
          //提取总长度字符串为一组
          const group = cleanLine.slice(i, i + totalLength)
          //从组里提取卡号
          const cardNumber = group.slice(0, this.cardNumberLength)
          //从组里提取卡密
          const cardKey = group.slice(this.cardNumberLength, totalLength)

          // 构建格式化字符串，先添加卡号
          let formatted = cardNumber
          //卡密不为空添加卡密
          if (cardKey) formatted += ` ${cardKey}`
          //最后添加换行符
          processed += formatted + '\n'
        }
        //将格式化后的添加到数组
        formattedLines.push(processed.trim());
      })
      // 更新输入框内容（保留光标位置），将数组所有行用换行符连接，并去掉首位空白
      this.$nextTick(() => {
        this.inputText = formattedLines.join('\n').trim()
      })
      console.log(this.inputText)
    },
    // 跳转到协议
    toDetail(url) {
      this.$app.openUrl(url, false)
    }
  }
}
</script>

<style lang="scss">
.container {
  height: 100vh;
  position: relative;
}

.divider {
  height: 2rpx;
  background-color: rgba(0, 0, 0, 0.09);
  margin: 0 45rpx;
}

.ph-style {
  color: rgba(0, 0, 0, 0.40);
}

.right-container {
  display: flex;
  align-items: center;
}

.card-scroll-container {
  white-space: nowrap;
  margin-bottom: 20rpx;
  padding: 0 40rpx;
  position: fixed;
  top: 200rpx; //web:88rpx wx:200rpx
  left: 0;
  width: 100%;
  background-color: white;
  box-sizing: border-box;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  z-index: 1;

  /* 添加一个上边距的背景遮挡 */
  &::before {
    content: '';
    position: absolute;
    top: -88rpx;
    left: 0;
    width: 100%;
    height: 88rpx;
    // background-color: white;
    z-index: -1;
  }

  .type-item {
    display: inline-block;
    padding: 20rpx 5rpx;
    margin-right: 45rpx;
    font-size: 32rpx;
    color: rgba(0, 0, 0, 0.45);
    cursor: pointer;
    border-bottom: 4rpx solid transparent;
    border-radius: 2px;

    &.active {
      color: #4D7EF4;
      font-weight: 700;
      border-bottom-color: #4D7EF4;
    }
  }
}

.content-container {
  .form-item {
    padding: 24rpx 38rpx;
    display: flex;
    justify-content: space-between;
    font-size: 28rpx;

    .label {
      color: #000;
    }

    .form-item-right {
      display: flex;
      align-items: center;
    }

    .hint {
      color: rgba(0, 0, 0, 0.40);
      margin-right: 22rpx;

      &.active {
        color: #000;
      }
    }
  }
}

.select-container {
  .discount-item {
    .fixed-discount {
      display: flex;
      justify-content: space-between;
      padding: 24rpx 38rpx;
      font-size: 28rpx;

      .label {
        color: #000;
        margin-right: 22rpx;
      }

      .form-item-right {
        display: flex;
        align-items: center;
      }

      .discount-input {
        font-size: 28rpx;
        color: #000;
        text-align: right;
      }

      .custom-last {
        font-size: 28rpx;
        color: #000;
      }
    }
  }

  .user-limit {
    display: flex;
    border-radius: 38rpx;
    justify-content: space-between;
    padding: 18rpx 26rpx;
    background-color: #FFF2D4;
    margin: 28rpx 15rpx;
  }

  .sub-type-container {
    display: flex;
    margin-top: 20rpx;
    margin-left: 34rpx;
    margin-bottom: 36rpx;

    .submit-type {
      display: flex;

      .type-btn {
        margin-right: 20rpx;
        padding: 10rpx 0;
        text-align: center;
        color: #666;
        cursor: pointer;
        border-bottom: 4rpx solid transparent;
        border-radius: 2px;
        font-size: 28rpx;

        &.active {
          color: #000;
          font-weight: 700;
          border-bottom-color: #4D7EF4;
        }
      }
    }
  }

  .input-container {
    padding: 0 32rpx;

    .input-group {

      .group-input {
        margin-bottom: 24rpx;
        background-color: #F0F0F0;
        padding: 24rpx 32rpx;
        display: flex;

        .label {
          color: rgba(0, 0, 0, 0.60);
          font-size: 32rpx;
        }

        .card-input {
          font-size: 32rpx;
          margin-left: 50rpx;
          background: #F0F0F0;
        }
      }
    }

    .card-input-area {
      height: 300rpx;
      width: 100%;
      padding: 20rpx;
      margin-bottom: 24rpx;
      font-size: 32rpx;
      background-color: #F0F0F0;
    }

    .tips {
      color: #999;
      font-size: 24rpx;

      .warning {
        color: #ff4444;
        font-size: 22rpx;
        margin-right: 10rpx;
      }
    }
  }

  .submit-btn {
    display: flex;
    position: fixed;
    bottom: 15rpx;
    height: 88rpx;
    width: 100%;
    // left: 50%;
    // transform: translateX(-50%);
    // border-radius: 8rpx;
    z-index: 999;
  }
}

/* 覆盖 iOS 默认隐藏行为 */
.custom-scroll ::-webkit-scrollbar {
  -webkit-appearance: auto !important;
  /* 强制显示 */
  opacity: 1 !important;
  /* 避免透明 */
}

/* 通用样式 */
::-webkit-scrollbar {
  width: 10rpx !important;
  background: transparent;
}

/* 仅针对 iOS 小程序 */
/* #ifdef MP-WEIXIN */
::-webkit-scrollbar {
  display: block !important;
  /* 覆盖 iOS 默认隐藏 */
}

::-webkit-scrollbar-thumb {
  background-color: #f7f7f7 !important;
  /* 你的自定义颜色 */
}

/* #endif */

.popup-container {
  height: 50vh;
  overflow: auto;
  padding: 32rpx 28rpx;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 46rpx;
    margin-left: 24rpx;

    .title {
      font-size: 28rpx;
      color: #000;
      font-weight: bold;
    }

    .close {
      height: 28rpx;
      width: 28rpx;
    }
  }

  .card-item-container {
    box-sizing: border-box;
    height: 154rpx;
    width: calc(100% - 32rpx);
    margin-bottom: 20rpx;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 2rpx solid #DCDCDC;
    border-radius: 14rpx;

    .item-image {
      height: 80rpx;
      width: 80rpx;
      margin-bottom: 14rpx;
    }

    .card-item-name {
      text-align: center;
      font-size: 24rpx;
      color: #171717;
    }
  }

  .card-item-fv-container {
    box-sizing: border-box;
    height: 118rpx;
    width: calc(100% - 20rpx);
    margin-bottom: 20rpx;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 2rpx solid #E5E5E5;
    border-radius: 14rpx;

    .card-item-name {
      text-align: center;
      font-size: 28rpx;
      color: #171717;
    }
  }

  .card-item-state {
    position: absolute;
    top: 0;
    right: 0;
    font-size: 20rpx;
    color: #fff;
    background-color: #ff4444;
    padding: 2rpx 10rpx;
    border-top-left-radius: 15px;
    /* 左上角 */
    border-bottom-right-radius: 15px;
    /* 右下角 */
  }
}

.commit-popup-container {
  padding: 34rpx;

  image {
    height: 24rpx;
    width: 24rpx;
  }
}

.card-scroll-placeholder {
  height: 120rpx;
  width: 100%;
}

.popup-auth-container {
  width: 578rpx;
  height: 590rpx;
  background-image: url('~@/static/images/ic_auth_pop_bg.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
}
</style>